<template>
  <!-- 搜索结果 -->
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      :error.sync="error"
      error-text="加载失败，请稍后重试"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell v-for="item in resultList" :key="item.art_id" :title="item.title" />
    </van-list>
  </div>
</template>

<script>
import { searchResult } from '@/api/search'
export default {
  props: {
    hadSearch: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      resultList: [],
      total: 0,
      page: 1,
      pagenum: 20,
      loading: false,
      error: false,
      finished: false
    }
  },
  created () {
  },
  methods: {
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const { data: res } = await searchResult({
          page: this.page,
          per_page: this.pagenum,
          q: this.hadSearch
        })
        console.log(res)
        const { results, total_count } = res.data
        this.resultList.push(...results)
        this.total = total_count
        // 加载状态结束
        this.loading = false

        // 数据全部加载完成
        if (results.length) {
          this.page++
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-result {
  padding-top: 114px;
}
</style>
